package com.work08.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.work08.common.R;
import com.work08.pojo.Category;
import com.work08.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 绛河
 * @date 2023/6/18
 * @apiNote
 */
@RestController
@RequestMapping("/api/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @GetMapping("/getAllByPage")
    public R<Page> getAllByPage(String categoryName, Integer currentPage, Integer pageSize) {
        System.out.println(categoryName);
        System.out.println(currentPage);
        System.out.println(pageSize);
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(categoryName != null && categoryName != "", Category::getName, categoryName);
        Page<Category> page1 = new Page<>(currentPage, pageSize);
        categoryService.page(page1, lambdaQueryWrapper);
        System.out.println("page" + page1.getRecords());
        return R.success(page1);
    }

    @PostMapping("/addCategory")
    public R<String> addCategory(@RequestBody Category category) {
        System.out.println(category);
        if (category.getName() == null || category.getName() == "") {
            return R.error("数据为空添加失败");
        }
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(category.getName() != null && category.getName() != "", Category::getName, category.getName());
        Category one = categoryService.getOne(lambdaQueryWrapper);
        if (one!=null){
            return R.error("该类别已经存在");
        }
        categoryService.save(category);
        return R.success("添加成功");
    }

    @PutMapping("/updateCategory")
    public R<String> updateCategory(@RequestBody Category category){
        categoryService.updateById(category);
        return R.success("更新成功");
    }

    @DeleteMapping("/deleteCategory")
    public R<String> deleteCategory(Integer id){
        categoryService.removeById(id);
        return R.success("删除成功");
    }


    @DeleteMapping("/deleteCategoryByBatch")
    public R<String> deleteCategoryByBatch(@RequestBody Integer[] ids){
        LambdaUpdateWrapper<Category> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.in(Category::getId,ids);
        categoryService.remove(lambdaUpdateWrapper);
        return R.success("删除成功");
    }

    @GetMapping("/getAll")
    public R<List<Category>> getAll(){
        List<Category> list = categoryService.list();
        return R.success(list);
    }
}
